package com.qfdu.repo.dao.impl;

import com.qfdu.repo.bean.Product;
import com.qfdu.repo.dao.ProductDao;
import com.qfdu.repo.db.DBUtils;
import com.qfdu.repo.db.PstCallback;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 沐辰
 * @version v1.0
 * @description:
 * @project Qfed2401
 * @Date 2024/5/9 11:12
 * @company qf
 */
public class ProductDaoImpl implements ProductDao {
    public List<Product> selectAll() {
        String sql = "select * from products";
        ResultSet resultSet = DBUtils.query(sql,null);
        List<Product> products = new ArrayList<Product>();
        try {
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String pno = resultSet.getString("pno");
                String pname = resultSet.getString("pname");
                String paddr = resultSet.getString("paddr");
                String pdate = resultSet.getString("pdate");
                String enterdate = resultSet.getString("enterdate");
                Product product = new Product(id,pno,pname,paddr,pdate,enterdate);
                products.add(product);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                    DBUtils.getClose();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return products;
    }

    public void add(final Product product) {
        String sql = "insert into products (pno,pname,paddr,pdate,enterdate) values (?,?,?,?,?)";
        DBUtils.executeUpdate(sql, new PstCallback() {
            public void pstSetValue(PreparedStatement pst) {
                try {
                    pst.setString(1,product.getPno());
                    pst.setString(2,product.getPname());
                    pst.setString(3,product.getPaddr());
                    pst.setString(4,product.getPdate());
                    pst.setString(5,product.getEnterdate());
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
